// #include <set>
#ifndef CLOUD_HPP
#define CLOUD_HPP


#include <WiFi.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "mbedtls/base64.h"
#include "bbl-certs.h"


String _region="China";
String _email="18559220052";
String _username="18559220052";
String _auth_token;
String _password="25845630";
// String ssid="218-3";
// String Password="218520520";


void connectToWifi(char* ssid, char*  Password){
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, Password);
    delay(1000);
    wl_status_t status = WiFi.status();
    
    bool reboot = false;
    const char *statusText = "";
    while (status != WL_CONNECTED)
    {

        switch (status)
        {
        case WL_IDLE_STATUS:
            statusText = " 连接中...";
            break;

        case WL_NO_SSID_AVAIL:
            statusText = " SSID错误";
            reboot = true;
            break;

            // case WL_CONNECTION_LOST:
            //     break;

        case WL_CONNECT_FAILED:
        case WL_DISCONNECTED:
            statusText = " 请检查WIFI凭据";
            reboot = true;
            break;

        default:
            break;
        }

        if (statusText != "")
        {
            Serial.println(statusText);
            delay(32);
        }

        if (reboot)
        {
            delay(3000);
            ESP.restart();
        }
        status = WiFi.status();
    }
}



String _getAuthToken()
{
    Serial.println("Getting accessToken from Bambu Cloud");
    String url = _region == "China" ? "https://api.bambulab.cn/v1/user-service/user/login" : "https://api.bambulab.com/v1/user-service/user/login";

    HTTPClient http;
    // http.begin(url, getRegionCert());
    http.setTimeout(30000);
    http.begin(url);
    http.addHeader("Content-Type", "application/json");

    String payload = "{\"account\":\"" + _email + "\",\"password\":\"" + _password + "\"}";

    int httpResponseCode = http.POST(payload);

    if (httpResponseCode != 200)
    {
        Serial.printf("Received error: %d\n", httpResponseCode);
        
        http.end();
        return "";
    }

    String response = http.getString();
    Serial.printf("Received response: %s\n", response.c_str());
    http.end();

    DynamicJsonDocument doc(4096);
    deserializeJson(doc, response);
    return doc["accessToken"].as<String>();
}

#endif // CLOUD_HPP